<?php
/**
 * @package		简易CMS
 * @subpackage	后台通用管理模块
 * @version		$Id: admincp_misc.php 25 2012-08-29 17:55:19Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

if(!defined('IN_JYCMS') || !defined('IN_ADMINCP')) {
	exit('Access Denied');
}

cpheader();

if($operation == 'link') {

	if(!submitcheck('linksubmit')) {

?>
<script type="text/JavaScript">
var rowtypedata = [
	[
		[1,'', 'td25'],
		[1,'<input type="text" class="txt" name="newdisplayorder[]" size="3">', 'td28'],
		[1,'<input type="text" class="txt" name="newname[]" size="15">'],
		[1,'<input type="text" class="txt" name="newurl[]" size="20">'],
		[1,'<input type="text" class="txt" name="newdescription[]" size="30">', 'td26'],
		[1,'<input type="text" class="txt" name="newlogo[]" size="20">']
	]
]
</script>
<?

		shownav('extended', 'misc_link');
		showtips('misc_link_tips');
		showformheader('misc&operation=link');
		showtableheader();
		showsubtitle(array('', 'display_order', 'misc_link_edit_name', 'misc_link_edit_url', 'misc_link_edit_description', 'misc_link_edit_logo'));

		$query = DB::query("SELECT * FROM #__common_friendlink ORDER BY displayorder");
		while($friendlink = DB::fetch($query)) {
			$type = sprintf('%04b', $friendlink['type']);
			showtablerow('', array('class="td25"', 'class="td28"', '', '', 'class="td26"'), array(
				'<input type="checkbox" class="checkbox" name="delete[]" value="'.$friendlink['id'].'" />',
				'<input type="text" class="txt" name="displayorder['.$friendlink[id].']" value="'.$friendlink['displayorder'].'" size="3" />',
				'<input type="text" class="txt" name="name['.$friendlink[id].']" value="'.$friendlink['name'].'" size="15" />',
				'<input type="text" class="txt" name="url['.$friendlink[id].']" value="'.$friendlink['url'].'" size="20" />',
				'<input type="text" class="txt" name="description['.$friendlink[id].']" value="'.$friendlink['description'].'" size="30" />',
				'<input type="text" class="txt" name="logo['.$friendlink[id].']" value="'.$friendlink['logo'].'" size="20" />',
			));
		}

		echo '<tr><td></td><td colspan="3"><div><a href="###" onclick="addrow(this, 0)" class="addtr">'.$lang['misc_link_add'].'</a></div></td></tr>';
		showsubmit('linksubmit', 'submit', 'del');
		showtablefooter();
		showformfooter();

	} else {

		if(is_array($_G['gp_delete'])) {
			$ids = $comma =	'';
			foreach((array)$_G['gp_delete'] as $id)	{
				$ids .=	"$comma'$id'";
				$comma = ',';
			}
			DB::delete('common_friendlink', "id IN ($ids)");
		}
		if(is_array($_G['gp_name'])) {
			foreach((array)$_G['gp_name'] as $id => $val) {
				DB::update('common_friendlink', array(
					'displayorder' => $_G['gp_displayorder'][$id],
					'name' => $_G['gp_name'][$id],
					'url' => $_G['gp_url'][$id],
					'description' => $_G['gp_description'][$id],
					'logo' => $_G['gp_logo'][$id],
				), array(
					'id' => $id,
				));
			}
		}

		if(is_array($_G['gp_newname'])) {
			foreach((array)$_G['gp_newname'] as $key => $value) {
				if($value) {
					DB::insert('common_friendlink', array(
						'displayorder' => $_G['gp_newdisplayorder'][$key],
						'name' => $value,
						'url' => $_G['gp_newurl'][$key],
						'description' => $_G['gp_newdescription'][$key],
						'logo' => $_G['gp_newlogo'][$key],
					));
				}
			}
		}

		updatecache('friendlinks');
		cpmsg('friendlinks_succeed', 'action=misc&operation=link', 'succeed');

	}

} elseif($operation == 'censor') {

	$ppp = 30;

	$addcensors = isset($_G['gp_addcensors']) ? trim($_G['gp_addcensors']) : '';

	if($do == 'export') {

		ob_end_clean();
		dheader('Cache-control: max-age=0');
		dheader('Expires: '.gmdate('D, d M Y H:i:s', TIMESTAMP - 31536000).' GMT');
		dheader('Content-Encoding: none');
		dheader('Content-Disposition: attachment; filename=CensorWords.txt');
		dheader('Content-Type: text/plain');

		$query = DB::query("SELECT find, replacement FROM #__common_word ORDER BY find ASC");
		while($censor = DB::fetch($query)) {
			$censor['replacement'] = str_replace('*', '', $censor['replacement']) <> '' ? $censor['replacement'] : '';
			echo $censor['find'].($censor['replacement'] != '' ? '='.dstripslashes($censor['replacement']) : '')."\n";
		}
		define('FOOTERDISABLED' , 1);
		exit();

	} elseif(submitcheck('addcensorsubmit') && $addcensors != '') {
		$oldwords = array();
		if($_G['adminid'] == 1 && $_G['gp_overwrite'] == 2) {
			DB::query("TRUNCATE #__common_word");
		} else {
			$query = DB::query("SELECT find, admin FROM #__common_word");
			while($censor = DB::fetch($query)) {
				$oldwords[md5($censor['find'])] = $censor['admin'];
			}
			DB::free_result($query);
		}

		$censorarray = explode("\n", $addcensors);
		$updatecount = $newcount = $ignorecount = 0;
		foreach((array)$censorarray as $censor) {
			list($newfind, $newreplace) = array_map('trim', explode('=', $censor));
			$newreplace = $newreplace <> '' ? daddslashes(str_replace("\\\'", '\'', $newreplace), 1) : '**';
			if(strlen($newfind) < 3) {
				$ignorecount ++;
				continue;
			} elseif(isset($oldwords[md5($newfind)])) {
				if($_G['gp_overwrite'] && ($_G['adminid'] == 1 || $oldwords[md5($newfind)] == $_G['member']['username'])) {
					$updatecount ++;
					DB::update('common_word', array(
						'replacement' => $newreplace,
					), "`find`='$newfind'");
				} else {
					$ignorecount ++;
				}
			} else {
				$newcount ++;
				DB::insert('common_word', array(
					'admin' => $_G['username'],
					'find' => $newfind,
					'replacement' => $newreplace,
				));
				$oldwords[md5($newfind)] = $_G['member']['username'];
			}
		}
		updatecache('censor');
		cpmsg('censor_batch_add_succeed', "action=misc&operation=censor&anchor=import", 'succeed', array('newcount' => $newcount, 'updatecount' => $updatecount, 'ignorecount' => $ignorecount));

	} elseif(!submitcheck('censorsubmit')) {
		$sqladd = '1';
		if(!empty($_G['gp_censorkeyword'])) {
			$censorkeyword = str_replace(array('%', '_'), array('\%', '\_'), $_G['gp_censorkeyword']);
			$sqladd .= " AND find LIKE '%{$censorkeyword}%'";
		}

		$ppp = 50;
		$startlimit = ($page - 1) * $ppp;

		shownav('topic', 'nav_posting_censor');
		$anchor = in_array($_G['gp_anchor'], array('list', 'import')) ? $_G['gp_anchor'] : 'list';
		showsubmenuanchors('nav_posting_censor', array(
			array('admin', 'list', $anchor == 'list'),
			array('misc_censor_batch_add', 'import', $anchor == 'import')
		));
		showtips('misc_censor_tips', 'list_tips', $anchor == 'list');
		showtips('misc_censor_batch_add_tips', 'import_tips', $anchor == 'import');

		showtagheader('div', 'list', $anchor == 'list');
		showformheader("misc&operation=censor&page=$page", '', 'keywordsearch');
		showtableheader();
		echo '<br /><br /><form method="post">'. $lang['keywords'].'<input type="text" name="censorkeyword" value="'.$_G['gp_censorkeyword'].'" /> &nbsp;<input type="submit" name="censor_search" value="'.$lang[search].'" class="btn" /></form>';
		showtablefooter();

		showformheader("misc&operation=censor&page=$page", '', 'listform');
		showtableheader('', 'fixpadding');
		showsubtitle(array('', 'misc_censor_word', 'misc_censor_replacement', 'operator'));
		$multipage = '';
		$totalcount = DB::result_first("SELECT count(*) FROM #__common_word WHERE $sqladd");
		if($totalcount) {
			$multipage = multi($totalcount, $ppp, $page, ADMINSCRIPT."?action=misc&operation=censor");
			$query = DB::query("SELECT * FROM #__common_word WHERE $sqladd ORDER BY find ASC LIMIT $startlimit, $ppp");
			while($censor =	DB::fetch($query)) {
				$censor['replacement'] = dstripslashes($censor['replacement']);
				$censor['replacement'] = dhtmlspecialchars($censor['replacement']);
				$censor['find'] = dhtmlspecialchars($censor['find']);
				$disabled = $_G['adminid'] != 1 && $censor['admin'] != $_G['member']['username'] ? 'disabled' : NULL;
				if(in_array($censor['replacement'], array('{BANNED}', '{MOD}'))) {
					$replacedisplay = 'style="display:none"';
					$optionselected = array();
					foreach(array('{BANNED}', '{MOD}') as $option) {
						$optionselected[$option] = $censor['replacement'] == $option ? 'selected' : '';
					}
				} else {
					$optionselected['{REPLACE}'] = 'selected';
					$replacedisplay = '';
				}
				showtablerow('', array('class="td25"', '', '', 'class="td26"'), array(
					"<input class=\"checkbox\" type=\"checkbox\" name=\"delete[]\" value=\"$censor[id]\" $disabled>",
					"<input type=\"text\" class=\"txt\" size=\"30\" name=\"find[$censor[id]]\" value=\"$censor[find]\" $disabled>",
					'<select name="replace['.$censor['id'].']" onchange="if(this.options[this.options.selectedIndex].value==\'{REPLACE}\'){$$$(\'divbanned'.$censor['id'].'\').style.display=\'\';$$$(\'divbanned'.$censor['id'].'\').value=\'\';}else{$$$(\'divbanned'.$censor['id'].'\').style.display=\'none\';}" '.$disabled.'>
					<option value="{BANNED}" '.$optionselected['{BANNED}'].'>'.cplang('misc_censor_word_banned').'</option><option value="{MOD}" '.$optionselected['{MOD}'].'>'.cplang('misc_censor_word_moderated').'</option><option value="{REPLACE}" '.$optionselected['{REPLACE}'].'>'.cplang('misc_censor_word_replaced').'</option></select>
					<input class="txt" type="text" size="10" name="replacecontent['.$censor['id'].']" value="'.$censor['replacement'].'" id="divbanned'.$censor['id'].'" '.$replacedisplay.' '.$disabled.'>',
					$censor['admin']
				));
			}
		}
		$misc_censor_word_banned = cplang('misc_censor_word_banned');
		$misc_censor_word_moderated = cplang('misc_censor_word_moderated');
		$misc_censor_word_replaced = cplang('misc_censor_word_replaced');
		echo <<<EOT
<script type="text/JavaScript">
	var rowtypedata = [
		[[1,''], [1,'<input type="text" class="txt" size="30" name="newfind[]">'], [1, ' <select onchange="if(this.options[this.options.selectedIndex].value==\'{REPLACE}\'){this.nextSibling.style.display=\'\';}else{this.nextSibling.style.display=\'none\';}" name="newreplace[]" $disabled><option value="{BANNED}">$misc_censor_word_banned</option><option value="{MOD}">$misc_censor_word_moderated</option><option value="{REPLACE}">$misc_censor_word_replaced</option></select><input class="txt" type="text" size="15" name="newreplacecontent[]" style="display:none;">'], [1,'']],
	];
	</script>
EOT;
		echo '<tr><td></td><td colspan="2"><div><a href="###" onclick="addrow(this, 0)" class="addtr">'.$lang['add_new'].'</a></div></td></tr>';

		showsubmit('censorsubmit', 'submit', 'del', '', $multipage, false);
		showtablefooter();
		showformfooter();
		showtagfooter('div');

		showtagheader('div', 'import', $anchor == 'import');
		showformheader("misc&operation=censor&page=$page", 'fixpadding');
		showtableheader('', 'fixpadding', 'importform');
		showtablerow('', 'class="vtop rowform"', '<br /><textarea name="addcensors" class="tarea" rows="10" cols="80"></textarea><br /><br />'.mradio('overwrite', array(
				0 => cplang('misc_censor_batch_add_no_overwrite'),
				1 => cplang('misc_censor_batch_add_overwrite'),
				2 => cplang('misc_censor_batch_add_clear')
		), '', FALSE));
		showsubmit('addcensorsubmit');
		showtablefooter();
		showformfooter();
		showtagfooter('div');

	} else {

		if($ids = dimplode($_G['gp_delete'])) {
			DB::delete('common_word', "id IN ($ids) AND ('{$_G['adminid']}'='1' OR admin='{$_G['username']}')");
		}

		if(is_array($_G['gp_find'])) {
			foreach((array)$_G['gp_find'] as $id => $val) {
				$_G['gp_find'][$id]  = $val = trim(str_replace('=', '', $_G['gp_find'][$id]));
				if(strlen($val) < 3) {
					cpmsg('censor_keywords_tooshort', '', 'error');
				}
				$_G['gp_replace'][$id] = $_G['gp_replace'][$id] == '{REPLACE}' ? $_G['gp_replacecontent'][$id] : $_G['gp_replace'][$id];
				$_G['gp_replace'][$id] = daddslashes(str_replace("\\\'", '\'', $_G['gp_replace'][$id]), 1);
				DB::update('common_word', array(
					'find' => $_G['gp_find'][$id],
					'replacement' => $_G['gp_replace'][$id],
				), "id='$id' AND ('{$_G['adminid']}'='1' OR admin='{$_G['username']}')");
			}
		}

		$newfind_array = !empty($_G['gp_newfind']) ? $_G['gp_newfind'] : array();
		$newreplace_array = !empty($_G['gp_newreplace']) ? $_G['gp_newreplace'] : array();
		$newreplacecontent_array = !empty($_G['gp_newreplacecontent']) ? $_G['gp_newreplacecontent'] : array();
		foreach((array)$newfind_array as $key => $value) {
			$newfind = trim(str_replace('=', '', $newfind_array[$key]));
			$newreplace  = trim($newreplace_array[$key]);

			if($newfind != '') {
				if(strlen($newfind) < 3) {
					cpmsg('censor_keywords_tooshort', '', 'error');
				}
				if($newreplace == '{REPLACE}') {
					$newreplace = daddslashes(str_replace("\\\'", '\'', $newreplacecontent_array[$key]), 1);
				}
				if($oldcenser = DB::fetch_first("SELECT admin FROM #__common_word WHERE find='$newfind'")) {
					cpmsg('censor_keywords_existence', '', 'error');
				} else {
					DB::insert('common_word', array(
						'admin' => $_G['username'],
						'find' => $newfind,
						'replacement' => $newreplace,
					));
				}
			}
		}

		updatecache('censor');
		cpmsg('censor_succeed', "action=misc&operation=censor&page=$page", 'succeed');

	}
} elseif($operation == 'cron') {

	if(empty($_G['gp_edit']) && empty($_G['gp_run'])) {

		if(!submitcheck('cronssubmit')) {

			shownav('tools', 'misc_cron');
			showsubmenu('nav_misc_cron');
			showtips('misc_cron_tips');
			showformheader('misc&operation=cron');
			showtableheader('', 'fixpadding');
			showsubtitle(array('', 'name', 'available', 'type', 'time', 'misc_cron_last_run', 'misc_cron_next_run', ''));

			$query = DB::query("SELECT * FROM #__common_cron ORDER BY type DESC");
			while($cron = DB::fetch($query)) {
				$disabled = $cron['weekday'] == -1 && $cron['day'] == -1 && $cron['hour'] == -1 && $cron['minute'] == '' ? 'disabled' : '';

				if($cron['day'] > 0 && $cron['day'] < 32) {
					$cron['time'] = cplang('misc_cron_permonth').$cron['day'].cplang('misc_cron_day');
				} elseif($cron['weekday'] >= 0 && $cron['weekday'] < 7) {
					$cron['time'] = cplang('misc_cron_perweek').cplang('misc_cron_week_day_'.$cron['weekday']);
				} elseif($cron['hour'] >= 0 && $cron['hour'] < 24) {
					$cron['time'] = cplang('misc_cron_perday');
				} else {
					$cron['time'] = cplang('misc_cron_perhour');
				}

				$cron['time'] .= $cron['hour'] >= 0 && $cron['hour'] < 24 ? sprintf('%02d', $cron[hour]).cplang('misc_cron_hour') : '';

				if(!in_array($cron['minute'], array(-1, ''))) {
					foreach((array)$cron['minute'] = explode("\t", $cron['minute']) as $k => $v) {
						$cron['minute'][$k] = sprintf('%02d', $v);
					}
					$cron['minute'] = implode(',', $cron['minute']);
					$cron['time'] .= $cron['minute'].cplang('misc_cron_minute');
				} else {
					$cron['time'] .= '00'.cplang('misc_cron_minute');
				}

				$cron['lastrun'] = $cron['lastrun'] ? dgmdate($cron['lastrun'], $_G['setting']['dateformat']."<\b\\r />".$_G['setting']['timeformat']) : '<b>N/A</b>';
				$cron['nextcolor'] = $cron['nextrun'] && $cron['nextrun'] + $_G['setting']['timeoffset'] * 3600 < TIMESTAMP ? 'style="color: #ff0000"' : '';
				$cron['nextrun'] = $cron['nextrun'] ? dgmdate($cron['nextrun'], $_G['setting']['dateformat']."<\b\\r />".$_G['setting']['timeformat']) : '<b>N/A</b>';

				showtablerow('', array('class="td25"', 'class="crons"', 'class="td25"', 'class="td25"', 'class="td23"', 'class="td23"', 'class="td23"', 'class="td25"'), array(
					"<input class=\"checkbox\" type=\"checkbox\" name=\"delete[]\" value=\"$cron[cronid]\" ".($cron['type'] == 'system' ? 'disabled' : '').">",
					"<input type=\"text\" class=\"txt\" name=\"namenew[$cron[cronid]]\" size=\"20\" value=\"$cron[name]\"><br /><b>$cron[filename]</b>",
					"<input class=\"checkbox\" type=\"checkbox\" name=\"availablenew[$cron[cronid]]\" value=\"1\" ".($cron['available'] ? 'checked' : '')." $disabled>",
					cplang($cron['type'] == 'system' ? 'inbuilt' : 'custom'),
					$cron[time],
					$cron[lastrun],
					$cron[nextrun],
					"<a href=\"".ADMINSCRIPT."?action=misc&operation=cron&edit=$cron[cronid]\" class=\"act\">$lang[edit]</a><br />".
					($cron['available'] ? " <a href=\"".ADMINSCRIPT."?action=misc&operation=cron&run=$cron[cronid]\" class=\"act\">$lang[misc_cron_run]</a>" : " <a href=\"###\" class=\"act\" disabled>$lang[misc_cron_run]</a>")
				));
			}

			showtablerow('', array('','colspan="10"'), array(
				cplang('add_new'),
				'<input type="text" class="txt" name="newname" value="" size="20" />'
			));
			showsubmit('cronssubmit', 'submit', 'del');
			showtablefooter();
			showformfooter();

		} else {

			if($ids = dimplode($_G['gp_delete'])) {
				DB::delete('common_cron', "cronid IN ($ids) AND type='user'");
			}

			if(is_array($_G['gp_namenew'])) {
				foreach((array)$_G['gp_namenew'] as $id => $name) {
					$newcron = array(
						'name' => dhtmlspecialchars($_G['gp_namenew'][$id]),
						'available' => $_G['gp_availablenew'][$id]
					);
					if(empty($_G['gp_availablenew'][$id])) {
						$newcron['nextrun'] = '0';
					}
					DB::update('common_cron', $newcron, "cronid='$id'");
				}
			}

			if($newname = trim($_G['gp_newname'])) {
				DB::insert('common_cron', array(
					'name' => dhtmlspecialchars($newname),
					'type' => 'user',
					'available' => '0',
					'weekday' => '-1',
					'day' => '-1',
					'hour' => '-1',
					'minute' => '',
					'nextrun' => $_G['timestamp'],
				));
			}

			$query = DB::query("SELECT cronid, filename FROM #__common_cron");
			while($cron = DB::fetch($query)) {
				if(!file_exists(ROOT_PATH.'./source/cron/'.$cron['filename'])) {
					DB::update('common_cron', array(
						'available' => '0',
						'nextrun' => '0',
					), "cronid='$cron[cronid]'");
				}
			}

			updatecache('setting');
			cpmsg('crons_succeed', 'action=misc&operation=cron', 'succeed');

		}

	} else {

		$cronid = empty($_G['gp_run']) ? $_G['gp_edit'] : $_G['gp_run'];
		$cron = DB::fetch_first("SELECT * FROM #__common_cron WHERE cronid='$cronid'");
		if(!$cron) {
			cpmsg('Undefined action, please return.', '', 'error');
		}
		$cron['filename'] = str_replace(array('..', '/', '\\'), array('', '', ''), $cron['filename']);
		$cronminute = str_replace("\t", ',', $cron['minute']);
		$cron['minute'] = explode("\t", $cron['minute']);

		if(!empty($_G['gp_edit'])) {

			if(!submitcheck('editsubmit')) {

				shownav('tools', 'misc_cron');
				showsubmenu($lang['misc_cron_edit'].' - '.$cron['name']);
				showtips('misc_cron_edit_tips');

				$weekdayselect = $dayselect = $hourselect = '';

				for($i = 0; $i <= 6; $i++) {
					$weekdayselect .= "<option value=\"$i\" ".($cron['weekday'] == $i ? 'selected' : '').">".$lang['misc_cron_week_day_'.$i]."</option>";
				}

				for($i = 1; $i <= 31; $i++) {
					$dayselect .= "<option value=\"$i\" ".($cron['day'] == $i ? 'selected' : '').">$i $lang[misc_cron_day]</option>";
				}

				for($i = 0; $i <= 23; $i++) {
					$hourselect .= "<option value=\"$i\" ".($cron['hour'] == $i ? 'selected' : '').">$i $lang[misc_cron_hour]</option>";
				}

				shownav('tools', 'misc_cron');
				showformheader("misc&operation=cron&edit=$cronid");
				showtableheader();
				showsetting('misc_cron_edit_weekday', '', '', "<select name=\"weekdaynew\"><option value=\"-1\">*</option>$weekdayselect</select>");
				showsetting('misc_cron_edit_day', '', '', "<select name=\"daynew\"><option value=\"-1\">*</option>$dayselect</select>");
				showsetting('misc_cron_edit_hour', '', '', "<select name=\"hournew\"><option value=\"-1\">*</option>$hourselect</select>");
				showsetting('misc_cron_edit_minute', 'minutenew', $cronminute, 'text');
				showsetting('misc_cron_edit_filename', 'filenamenew', $cron['filename'], 'text');
				showsubmit('editsubmit');
				showtablefooter();
				showformfooter();

			} else {

				$daynew = $_G['gp_weekdaynew'] != -1 ? -1 : $_G['gp_daynew'];
				if(strpos($_G['gp_minutenew'], ',') !== FALSE) {
					$minutenew = explode(',', $_G['gp_minutenew']);
					foreach((array)$minutenew as $key => $val) {
						$minutenew[$key] = $val = intval($val);
						if($val < 0 || $var > 59) {
							unset($minutenew[$key]);
						}
					}
					$minutenew = array_slice(array_unique($minutenew), 0, 12);
					$minutenew = implode("\t", $minutenew);
				} else {
					$minutenew = intval($_G['gp_minutenew']);
					$minutenew = $minutenew >= 0 && $minutenew < 60 ? $minutenew : '';
				}

				if(preg_match("/[\\\\\/\:\*\?\"\<\>\|]+/", $_G['gp_filenamenew'])) {
					cpmsg('crons_filename_illegal', '', 'error');
				} elseif(!is_readable(ROOT_PATH.($cronfile = "./source/cron/{$_G['gp_filenamenew']}"))) {
					cpmsg('crons_filename_invalid', '', 'error', array('cronfile' => $cronfile));
				} elseif($_G['gp_weekdaynew'] == -1 && $daynew == -1 && $_G['gp_hournew'] == -1 && $minutenew === '') {
					cpmsg('crons_time_invalid', '', 'error');
				}

				DB::update('common_cron', array(
					'weekday' => $_G['gp_weekdaynew'],
					'day' => $daynew,
					'hour' => $_G['gp_hournew'],
					'minute' => $minutenew,
					'filename' => trim($_G['gp_filenamenew']),
				), "cronid='$cronid'");

				updatecache('crons');

				cmsCron::run($cronid);

				cpmsg('crons_succeed', 'action=misc&operation=cron', 'succeed');

			}

		} else {

			if(!file_exists(ROOT_PATH.($cronfile = "./source/cron/$cron[filename]"))) {
				cpmsg('crons_run_invalid', '', 'error', array('cronfile' => $cronfile));
			} else {
				cmsCron::run($cron['cronid']);
				cpmsg('crons_run_succeed', 'action=misc&operation=cron', 'succeed');
			}

		}

	}

} elseif($operation == 'custommenu') {

	if(!$do) {

		if(!submitcheck('optionsubmit')) {
			$mpp = 10;
			$startlimit = ($page - 1) * $mpp;
			$num = DB::result_first("SELECT count(*) FROM #__common_admincp_cmenu WHERE uid='$_G[uid]' AND sort='1'");
			$multipage = multi($num, $mpp, $page, ADMINSCRIPT.'?action=misc&operation=custommenu');
			$optionlist = $ajaxoptionlist = '';
			$query = DB::query("SELECT id, title, displayorder, url FROM #__common_admincp_cmenu WHERE uid='$_G[uid]' AND sort='1' ORDER BY displayorder, dateline DESC, clicks DESC LIMIT $startlimit, $mpp");
			while($custom = DB::fetch($query)) {
				$custom['url'] = rawurldecode($custom['url']);
				$optionlist .= showtablerow('', array('class="td25"', 'class="td28"', '', 'class="td26"'), array(
					"<input type=\"checkbox\" class=\"checkbox\" name=\"delete[]\" value=\"$custom[id]\">",
					"<input type=\"text\" class=\"txt\" size=\"3\" name=\"displayordernew[$custom[id]]\" value=\"$custom[displayorder]\">",
					"<input type=\"text\" class=\"txt\" size=\"25\" name=\"titlenew[$custom[id]]\" value=\"".cplang($custom['title'])."\"><input type=\"hidden\" name=\"langnew[$custom[id]]\" value=\"$custom[title]\">",
					"<input type=\"text\" class=\"txt\" size=\"40\" name=\"urlnew[$custom[id]]\" value=\"$custom[url]\">"
				), TRUE);
				$ajaxoptionlist .= '<li><a href="'.$custom['url'].'" target="'.(substr(rawurldecode($custom['url']), 0, 17) == ADMINSCRIPT.'?action=' ? 'main' : '_blank').'">'.cplang($custom['title']).'</a></li>';
			}

			echo <<<EOT
<script type="text/JavaScript">
	var rowtypedata = [
		[
			[1,'', 'td25'],
			[1,'<input type="text" class="txt" name="newdisplayorder[]" size="3">', 'td28'],
			[1,'<input type="text" class="txt" name="newtitle[]" size="25">'],
			[1,'<input type="text" class="txt" name="newurl[]" size="40">', 'td26']
		]
	];
</script>
EOT;
			shownav('tools', 'nav_custommenu');
			showsubmenu('nav_custommenu');
			showformheader('misc&operation=custommenu');
			showtableheader();
			showsubtitle(array('', 'display_order', 'name', 'URL'));
			echo $optionlist;
			echo '<tr><td></td><td colspan="3"><div><a href="###" onclick="addrow(this, 0)" class="addtr">'.$lang['custommenu_add'].'</a></div></td></tr>';
			showsubmit('optionsubmit', 'submit', 'del', '', $multipage);
			showtablefooter();
			showformfooter();

		} else {

			if($ids = dimplode($_G['gp_delete'])) {
				DB::query("DELETE FROM #__common_admincp_cmenu WHERE id IN ($ids) AND uid='$_G[uid]'");
			}

			if(is_array($_G['gp_titlenew'])) {
				foreach((array)$_G['gp_titlenew'] as $id => $title) {
					$_G['gp_urlnew'][$id] = rawurlencode($_G['gp_urlnew'][$id]);
					$title = dhtmlspecialchars($_G['gp_langnew'][$id] && lang($_G['gp_langnew'][$id], false) ? $_G['gp_langnew'][$id] : $title);
					$ordernew = intval($_G['gp_displayordernew'][$id]);
					DB::query("UPDATE #__common_admincp_cmenu SET title='$title', displayorder='$ordernew', url='".dhtmlspecialchars($_G['gp_urlnew'][$id])."' WHERE id='$id'");
				}
			}

			if(is_array($_G['gp_newtitle'])) {
				foreach((array)$_G['gp_newtitle'] as $k => $v) {
					$_G['gp_urlnew'][$k] = rawurlencode($_G['gp_urlnew'][$k]);
					DB::query("INSERT INTO #__common_admincp_cmenu (title, displayorder, url, sort, uid) VALUES ('".dhtmlspecialchars($v)."', '".intval($_G['gp_newdisplayorder'][$k])."', '".dhtmlspecialchars($_G['gp_newurl'][$k])."', '1', '$_G[uid]')");
				}
			}

			updatemenu('index');
			cpmsg('custommenu_edit_succeed', 'action=misc&operation=custommenu', 'succeed');

		}

	} elseif($do == 'add') {

		if($_G['gp_title'] && $_G['gp_url']) {
			admincustom($_G['gp_title'], dhtmlspecialchars($_G['gp_url']), 1);
			updatemenu('index');
			cpmsg('custommenu_add_succeed', rawurldecode($_G['gp_url']), 'succeed', array('title' => cplang($_G['gp_title'])));
		} else {
			cpmsg('Undefined action, please return.', '', 'error');
		}
	}

} elseif ($operation == 'spider'){
	if($do=='view'){
		$name=trim($_GET['name']);
		$day=(int)($_GET['day']);
		if($name=="")$this->message("名称不能为空","admin.php?m=spider&a=ls");
		if($day<1)$this->message("时间周期不能小于1","admin.php?m=spider&a=ls");
		$date_from=date("Ymd",time()-($day*86400));
		$date_to=date("Ymd");
		$sql="SELECT *
			FROM #__spider_log
			where
				`name` ='$name'
				and (`date`>{$date_from} and `date`<={$date_to})";
		$query=$db->Query($sql);
		$times=0;
		while ($row=$db->fetch_array($query)) {
			$row['first_visit']=dgmdate($row['first_visit'],"H:i:s", 0);
			$row['last_visit']=dgmdate($row['last_visit'],"H:i:s", 0);
			$times+=$row['times'];
			$log_list[]=$row;
		}
		$count=sizeof($log_list);
		$nav = cplang('spider_visit_log', array('name'=>$name, 'day'=>$day, 'count'=>$count));
		shownav('extended', $nav);
		showsubmenu($nav);
		showtableheader();
		showsubtitle(
			array(
				'spder_date',
				'spder_times',
				'first_visit',
				'last_visit'
			)
		);
		foreach((array)$log_list as $robot) {
			$type = sprintf('%04b', $friendlink['type']);
			showtablerow('',
				'',
				array(
				$robot['date'],
				$robot['times'],
				$robot['first_visit'],
				$robot['last_visit']
			));
		}
		showtablefooter();

	} else {
		$url = 'admin.php?action=misc&operation=spider&do=ls';
		$order_by=$_G['gp_order_by']?$_G['gp_order_by']:"today_times";
		$order_type=$_G['gp_order_type']?$_G['gp_order_type']:"desc";
		$toggle_order_type=$order_type=="desc"?"asc":"desc";
		$$order_by="order_".$order_type;
		$sql="SELECT * FROM #__spider";
		$query=DB::Query($sql,"SKIP_ERROR");
		$robot_list=array();
		$name_list=array();
		while ($row=DB::fetch_array($query)) {
			$row['link']=preg_replace("/.*?(((((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k):\/\/)|(www\.))([^\[\"'\s\)\(\;]+))|([a-z0-9\_\-.]+@[a-z0-9]+\.[a-z0-9\.]{2,}))*/i","\\1",$row['agent']);
			if(strpos($row['link'],'@')!==false)$row['link']="mailto:".$row['link'];
			if($row['link'] && strpos($row['link'],":")===false)$row['link']="http:/"."/".$row['link'];
			$row['first_visit']=dgmdate($row['first_visit'],"Y-m-d", -getglobal('member/timeoffset'));
			$row['last_visit']=dgmdate($row['last_visit'],"Y-m-d", -getglobal('member/timeoffset'));
			$row['today_times']=0;
			$name_list[]=$row['name'];
			$row['name']=trim($row['name']);
			$robot_list[$row['name']]=$row;
		}
		$today = date("Y-m-d",time());
		if(sizeof($name_list)>0) {
			$names=implode("','",$name_list);
			$names = "'".$names."'";
			$sql="SELECT * FROM #__spider_log
				where
					`name` in($names)
					and `date`='$today'
				order by times desc";
			$query=DB::Query($sql,"SKIP_ERROR");
			$today_robot_list=array();
			while ($row=DB::fetch_array($query)) {
				if(isset($robot_list[$row['name']]))
				$robot_list[$row['name']]['today_times']=$row['times'];
			}
		}

		if(is_array($robot_list) && sizeof($robot_list)>0) {
			foreach ($robot_list as $key=>$value) {
				$order_by_list[$key]=$value[$order_by];
			}
			array_multisort($order_by_list,constant(strtoupper("sort_".$order_type)),$robot_list);
		}
		if(sizeof($robot_list)>0) {
			$robot_ip_list=array();
			$sql="SELECT ip,name from #__spider_ip order by `ip`";
			$query=DB::Query($sql,"SKIP_ERROR");
			if($query!=false) {
				while ($row=DB::fetch_array($query)) {
					$robot_ip_list[$row['name']][]=$row['ip'];
				}
				if(!empty($robot_ip_list)) {
					foreach ($robot_ip_list as $_robot=>$_ip_list) {
						if(sizeof($_ip_list)>5) {
							$ip_list=array();
							$ip_list_count=0;
							foreach ($_ip_list as $_ip) {
								$ip=substr($_ip,0,strrpos($_ip,".")).".*";
								$ip_list[$ip]=$ip;
								$ip_list_count++;
								if($ip_list_count>10)break;
							}
						} else {
							$ip_list = $_ip_list;
						}
						$robot_ip_list[$_robot]=implode('<br />', $ip_list);
					}
				}
			}
		}
//pre($robots);pre($robot_ip_list);pre($robot_list);exit;

		shownav('extended', 'Spider log');
		showsubmenu('Spider log');
		showtips('spider_log_tips');
		showformheader('misc&operation=spider');
		showtableheader();
		showsubtitle(
			array(
				'<input class="checkbox" type="checkbox" name="portalall" onclick="checkAll(\'prefix\', this.form, \'delete\', \'portalall\')">',
				'spder_name',
				'today_times',
				'total_times',
				'last_time',
				'IP',
				'view_log'
			)
		);
		foreach((array)$robot_list as $robot) {
			$type = sprintf('%04b', $friendlink['type']);
			showtablerow('',
				array('class="td25"', 'class="td28"', '', '', 'class="td26"'),
				array(
				'<input type="checkbox" class="checkbox" name="delete[]" value="'.$friendlink['id'].'" />',
				$robot['link']?'<a href="'.$robot['link'].'" target="_blank" title="' .$robot['agent'].'">'.$robot['name'].'</a>':'<span title="'.$robot[agent].'">'.$robot[name].'</span>',
				$robot[today_times],
				$robot[times],
				$robot[last_visit],
				'<a href="admin.php?action=misc&operation=spider&do=viewip&robot='.$robot[name].'" title="'.cplang('View detailed record').'">'.$robot_ip_list[$robot[name]].'</a>',
				'
				<a href="admin.php?action=misc&operation=spider&do=view&name='.$robot[name].'&day=5">5'.cplang('days').'</a>
				<a href="admin.php?action=misc&operation=spider&do=view&name='.$robot[name].'&day=15">15'.cplang('days').'</a>
				<a href="admin.php?action=misc&operation=spider&do=view&name='.$robot[name].'&day=30">30'.cplang('days').'</a>
				'
			));
		}

		showsubmit('linksubmit', 'submit', 'del');
		showtablefooter();
		showformfooter();
	}
}

?>